﻿using ShiQuan.AppUpdateBLL;
using ShiQuan.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace ShiQuan.AppUpdater
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //MessageBox.Show("debug");
            string appPath = string.Empty;
            if(args != null && args.Length > 0)
            {
                Logger.Info("args[0]=" + args[0]);
                string[] fieldValues = System.Web.HttpUtility.UrlDecode(args[0]).Split('|');
                if(fieldValues.Length > 0)
                {
                    for (int index = 0; index < fieldValues.Length; index++)
                    {
                        string[] fieldValue = fieldValues[index].Split('=');
                        if (fieldValue == null || fieldValue.Length <= 1)
                            continue;

                        if (fieldValue[0].ToLower() == "AppPath".ToLower())
                            appPath = System.Web.HttpUtility.UrlDecode(fieldValue[1]);
                    }
                }
            }
            if(string.IsNullOrEmpty(appPath))
            {
                Application.Run(new FrmMain());
            }
            else
            {
                try
                {
                    Logger.Info("appPath=" + appPath);
                    AppUpdaterBLL bll = new AppUpdaterBLL();
                    string error = string.Empty;
                    Logger.Info("读取程序本地信息...");
                    var appLocal = bll.GetLocalInfo(appPath, out error);
                    if (appLocal == null)
                    {
                        Logger.Error(error);
                        return;
                    }
                    Logger.Info("读取服务器程序信息..."+appLocal.ServerUrl);
                    var appServer = bll.GetServerInfo(appLocal, out error);
                    if (appServer == null)
                    {
                        Logger.Error(error);
                        return;
                    }
                    Logger.Info("判断是否需要更新程序...");
                    if(bll.CheckUpdate(appLocal,appServer) == false)
                    {
                        Logger.Info("未检查到需要更新的程序！");
                        return;
                    }
                    Application.Run(new FrmDebug(appPath,appLocal,appServer));
                }
                catch (Exception ex)
                {
                    Logger.Error("运行信息异常：" + ex.ToString());
                }
            }
            
        }
    }
}
